<template>
  <div>
    <el-form ref="form" :model="deptForm" label-width="100px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="deptForm.manager" placeholder="请选择">
          <el-option
            v-for="item in employee"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="deptForm.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="hSubmit">确认</el-button>
        <el-button @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    //   接收父级ID
    parentId: {
      type: String,
      required: true
    },
    // 是否是编辑
    isEdit: {
      type: Boolean,
      default: false

    },
    // 接受父组件传过来的格式化的数组，判断部门名称是否存在用
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验部门名称是否存在
    const validName = (rule, value, callback) => {
      // 因为子级pid等于父级id，筛选出与父级id相同的子级，再把子级的name取出
      console.log(this.parentId)
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)

      if (this.isEdit) {
        // 获取自身的对应的那个对象
        const dept = this.originList.find(item => item.id === this.parentId)
        // 获取父级id
        const fatherId = dept.pid
        existNameList = this.originList.filter(item => item.pid === fatherId && item.id !== this.parentId).map(item => item.name)
      }
      existNameList.includes(value) ? callback(new Error('部门名称' + value + '已经存在')) : callback()
    }
    // 校验部门编码是否重复
    const validCode = (rule, value, callback) => {
    // 判断是否能否找到对应的部门，如果找到了则返回该对象
      let existCodeList = this.originList.map(item => item.code)
      // 编辑的时候，为了防止部门编码显示已存在，需要把对应的编码给移除
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      // 如果存在该对象，则说明编码已经存在，抛出错误
      existCodeList.includes(value) ? callback(new Error('编码' + value + '已经存在')) : callback()
    }
    return {
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employee: [], // 树状数据结构
      rules: { // 校验规则
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }

        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取部门负责人数据方法
    this.getEmployeeData()
    // 数据回填
    this.getDepartDetail()
  },
  methods: {

    // 获取部门负责人数据
    async getEmployeeData() {
      const res = await getEmployeeSimple()
      console.log(res)
      this.employee = res.data
    },

    // 获取数据回填的信息
    async  getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        // console.log(res)
        this.deptForm = res.data // 把数据会填的数据赋值给deptForm
      }
    },
    // 添加部门
    async addDepartments() {
      // 调用添加部门接口
      await addDepartments({ ...this.deptForm, pid: this.parentId })
      //   console.log(res)
      // 通知父级关闭弹窗
      this.$emit('update-dialog')
    },

    // 编辑部门
    async editDepartments() {
      // 调用编辑部门接口
      await updateDepartments(this.deptForm)
      // 通知父级关闭弹窗
      this.$emit('update-dialog')
    },

    // 点击弹窗确认按钮
    hSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.isEdit ? this.editDepartments() : this.addDepartments()
        }
      })
    },

    // 点击弹窗取消按钮
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>

<style>
form.el-form {
  padding: 0 60px 0 20px;
}
.el-select {
  width: 100%;
}
</style>
